package dtt;

import java.sql.*;

public class SecurityBO {
	public UserBean authenticateUser(UserBean userbean) {

		Connection con = DBConnection.getConnection();
		String template = "Select userId,userName,userPassword from t_user where userName=?";
		boolean flag = false;

		String userId = userbean.getUserName();
		System.out.print("User ID in securitybo" + userId);
		String password = userbean.getUserPassword();
		String role = null;
		int userIdd = 0;
		UserBean userbean1 = null;
		try {
			PreparedStatement ps = con.prepareStatement(template);
			ps.setString(1, userId);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				String pwd = rs.getString("userPassword");
				if (pwd.equals(password)) {
				System.out.println("Login successful for "+userId);
					flag = true;
					//role = rs.getString("userRole");
					userIdd = rs.getInt("userId");
					System.out.println("Role is" + role);

				}// End of inner if
			}// End of outer if
			ps.close();
		}// end of try
		catch (SQLException e) {
			e.printStackTrace();
		}

		if (flag) {
			System.out.println("Flag is " + flag);
			userbean1 = new UserBean();
			userbean1.setUserName(userId);
			userbean1.setUserId(userIdd);
			template = "Select roleDesc from t_role where userId=?";
			try{
			PreparedStatement ps = con.prepareStatement(template);
			ps.setInt(1, userIdd);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				if (role == null){
				role = rs.getString("roleDesc");
				}else
				{
					role = role +","+ rs.getString("roleDesc");
				}
			}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			userbean1.setUserRole(role);
			System.out
					.println("UserID in bean if loop" + userbean1.getUserId());
			System.out.println("Role in bean in if loop"
					+ userbean1.getUserRole());
		}
		DBConnection.releaseConnection(con);
		con = null;
		// System.out.println("UserID in bean"+userbean1.getUserId());
		// System.out.println("UserID in bean"+userbean1.getUserRole());
		return userbean1;

	}
}
